/*
 * 自动保存管理器文件
*/

#include "ConfigReaderWriter.h"
#include <thread>
#include <atomic>
#include <vector>
#include <mutex>
#include <sstream>
#include<iterator>
#include <fstream>

//自动保存管理器
class AutoSaveManager:public ConfigReaderWriter
{
public:
    AutoSaveManager(std::string fileAddress, int autosave_interval)
        : m_autosave_active(false), m_autosave_interval_sec(autosave_interval)
    {
        if(fileAddress.length()>0)
            StartAutoSave(fileAddress, autosave_interval);
    }
    ~AutoSaveManager() {
        StopAutoSave();
    }
public:
//    virtual bool LoadFIle(std::string fileAddress)=0;
//    virtual bool SaveFile(std::string fileAddress)=0;
    // 自动保存线程函数
    void autosave_worker() {
        while (m_autosave_active) {
            std::this_thread::sleep_for(std::chrono::seconds(m_autosave_interval_sec));
            SaveFile(m_fileAddress_);
        }
    }
    // 启动自动保存
    virtual void StartAutoSave(const std::string& filename, int interval_sec = 300) {
        StopAutoSave();
        m_fileAddress_ = filename;
        m_autosave_interval_sec = interval_sec;
        m_autosave_active = true;
        m_autosave_thread = std::thread(&AutoSaveManager::autosave_worker, this);
    }
    // 停止自动保存
     void StopAutoSave() {
         if (m_autosave_active) {
             m_autosave_active = false;
             if (m_autosave_thread.joinable()) {
                 m_autosave_thread.join();
             }
         }
     }
protected:
    std::atomic<bool> m_autosave_active;//是否自动保存
    int m_autosave_interval_sec;//保存间隔(毫秒)
    std::thread m_autosave_thread;//保存线程
};

//正文章节管理器
class ChapterAutoSaveManager:public AutoSaveManager
{
public:
    ChapterAutoSaveManager(std::string fileAddress, int autosave_interval);
    ~ChapterAutoSaveManager(){
        SaveFile(m_fileAddress_);
    }

public:
    virtual bool LoadFIle(std::string fileAddress);
    virtual bool SaveFile(std::string fileAddress = std::string());

    // 统计字数（UTF-8安全）
    size_t CountWords(const std::string& str) {
        std::istringstream iss(str);
        return std::distance(std::istream_iterator<std::string>(iss),
                             std::istream_iterator<std::string>());
    }
    //统计章节数
    size_t CountChapters()const {
        return m_chapters.size();
    }

    // 设置书籍元数据
    void SetMetadata(const std::string& title, const std::string& author_name) {
        std::lock_guard<std::mutex> lock(m_data_mutex);
        m_book_title = title;
        m_author = author_name;
    }

    //读取章节
    void get_chapter(int idx, std::string& title_in, std::string& content_in,
                     std::string& summary_in){
        title_in = m_chapters[idx].title;
        content_in =m_chapters[idx].content;
        summary_in = m_chapters[idx].summary;
    }

    // 添加新章节
    void add_chapter(const std::string& title, const std::string& content,
                   const std::string& summary = "") {
        std::lock_guard<std::mutex> lock(m_data_mutex);

        Chapter ch;
        ch.title = title;
        ch.content = content;
        ch.summary = summary;
        ch.last_modified = std::time(nullptr);
        ch.word_count = CountWords(content);

        m_chapters.push_back(ch);
        m_table_of_contents.push_back(title);
    }

    bool remove_chapter(size_t idx){
        if(idx>m_chapters.size() || idx>m_table_of_contents.size())
            return false;
        //删除目录
        size_t i=0;
        auto it = m_chapters.begin();
        for(it = m_chapters.begin();it!=m_chapters.end();++it,++i){
            if(i==idx)
                break;
        }
        if(it!=m_chapters.end())
            m_chapters.erase(it);

        //删除正文
        i=0;
        auto it2 = m_table_of_contents.begin();
        for(it2 = m_table_of_contents.begin();it2!=m_table_of_contents.end();++it2,++i){
            if(i==idx)
                break;
        }
        if(it2!=m_table_of_contents.end())
            m_table_of_contents.erase(it2);

        return true;
    }

    // 更新章节内容
    void update_chapter(size_t index, const std::string& content,
                       const std::string& summary = "") {
        std::lock_guard<std::mutex> lock(m_data_mutex);
        if (index < m_chapters.size()) {
            m_chapters[index].content = content;
            m_chapters[index].summary = summary;
            m_chapters[index].last_modified = std::time(nullptr);
            m_chapters[index].word_count = CountWords(content);
        }
    }

protected:
    // 二进制写入字符串（带长度前缀）
    void WriteString(std::ofstream& file, const std::string& str) {
        uint32_t length = static_cast<uint32_t>(str.size());
        file.write(reinterpret_cast<const char*>(&length), sizeof(length));
        file.write(str.data(), length);
    }

    // 二进制读取字符串
    std::string ReadString(std::ifstream& file) {
        uint32_t length;
        file.read(reinterpret_cast<char*>(&length), sizeof(length));
        std::string str(length, '\0');
        file.read(&str[0], length);
        return str;
    }

    // 保存到文件
    bool save_to_file(const std::string& fileaddress) {
        std::lock_guard<std::mutex> lock(m_data_mutex);

        try {
            std::ofstream file(fileaddress, std::ios::binary);
            if (!file.is_open())
            {
                CreateFile(fileaddress);
                file.open(fileaddress);
                if(!file.is_open())
                    return false;
            }

//            // 文件头标识和版本//增加额外的版本控制模块专门控制
//            const char header[8] = {'N', 'O', 'V', 'E', 'L', 'U', '8', 0x01};
//            file.write(header, 8);

            // 写入元数据
            WriteString(file, m_book_title);
            WriteString(file, m_author);

            // 写入目录
            uint32_t toc_size = static_cast<uint32_t>(m_table_of_contents.size());
            file.write(reinterpret_cast<const char*>(&toc_size), sizeof(toc_size));
            for (const auto& item : m_table_of_contents) {
                WriteString(file, item);
            }

            // 写入章节数据
            uint32_t chapters_size = static_cast<uint32_t>(m_chapters.size());
            file.write(reinterpret_cast<const char*>(&chapters_size), sizeof(chapters_size));
            for (const auto& ch : m_chapters) {
                WriteString(file, ch.title);
                WriteString(file, ch.content);
                WriteString(file, ch.summary);
                file.write(reinterpret_cast<const char*>(&ch.last_modified), sizeof(ch.last_modified));
                file.write(reinterpret_cast<const char*>(&ch.word_count), sizeof(ch.word_count));
            }

            m_fileAddress_ = fileaddress;
            return true;
        }
        catch (...) {
            return false;
        }
    }

    // 从文件加载
    bool load_from_file(const std::string& fileaddress) {
        std::lock_guard<std::mutex> lock(m_data_mutex);

        try {
            std::ifstream file(fileaddress, std::ios_base::binary | std::ios_base::in);
            if (!file.is_open()){
                // 如果文件不存在，则创建一个新的文件
                CreateFile(fileaddress);
                // 创建成功后，重新打开文件进行读取
                file.clear(); // 重置文件的状态标志
                file.open(fileaddress, std::ios_base::binary);
                if (!file) {
                    return false;
                }

            }

//            // 验证文件头//增加额外的版本控制模块专门控制
//            char header[8];
//            file.read(header, 8);
//            if (std::string(header, 8) != std::string("NOVELU8\x01", 8)) {
//                return false;
//            }

            // 读取元数据
            m_book_title = ReadString(file);
            m_author = ReadString(file);

            // 读取目录
            uint32_t toc_size;
            file.read(reinterpret_cast<char*>(&toc_size), sizeof(toc_size));
            m_table_of_contents.resize(toc_size);
            for (auto& item : m_table_of_contents) {
                item = ReadString(file);
            }

            // 读取章节数据
            uint32_t chapters_size;
            file.read(reinterpret_cast<char*>(&chapters_size), sizeof(chapters_size));
            m_chapters.resize(chapters_size);
            for (auto& ch : m_chapters) {
                ch.title = ReadString(file);
                ch.content = ReadString(file);
                ch.summary = ReadString(file);
                file.read(reinterpret_cast<char*>(&ch.last_modified), sizeof(ch.last_modified));
                file.read(reinterpret_cast<char*>(&ch.word_count), sizeof(ch.word_count));
            }

            m_fileAddress_ = fileaddress;
            return true;
        }
        catch (...) {
            return false;
        }
    }

public:
    struct Chapter {
        std::string title;     // UTF-8编码
        std::string content;   // 保留原始换行符
        std::string summary;   // 章节梗概
        time_t last_modified;  // 最后修改时间
        size_t word_count;     // 字数统计
    };
protected:
    std::string m_book_title;//书名
    std::string m_author;//作者
    std::vector<Chapter> m_chapters;//每一章
    std::vector<std::string> m_table_of_contents;//正文列表
    std::mutex m_data_mutex;//锁
};
